package com.hd.appcommon.parse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: hzp
 * @date: 2022/3/24
 * @description:
 */
public class DDFormParser implements ParseDDForm {

    private static final SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public <T> T parseFrom(JSONObject data, Map<String, String> map, Class<T> clazz) throws IllegalAccessException, InstantiationException {

        T obj = clazz.newInstance();

        if ("ok".equals(data.get("errmsg"))) {
            List<FormComponent> formComponents = JSONArray.parseArray(
                    JSON.toJSONString(data.getJSONObject("process_instance").get("form_component_values")),
                    FormComponent.class);

            for (FormComponent formComponent : formComponents) {
                String name = map.get(formComponent.getName());
                String type = formComponent.getComponent_type();
                String val = formComponent.getValue();
                if (!val.isEmpty() && !val.equals("null"))
                    this.setval(name, val, type, obj);
            }
        }
        return obj;
    }

    public <T> void setval(String propertyName, String propertyVal, String type, T obj) {
        Field field;
        try {
            if (!isExistField(propertyName, obj))
                return;

            field = obj.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            if ("DDDateField".equals(type)) {
                if (16 == propertyVal.length()) {
//                    格式为年月日 时分
                    propertyVal = propertyVal + ":00";

                }
                if (10 == propertyVal.length()) {
                    propertyVal = propertyVal + " 00:00:00";
                }

                Date parse = ymdhms.parse(propertyVal);
                field.set(obj, parse);
                return;
            }
            field.set(obj, propertyVal);
        } catch (NoSuchFieldException | IllegalAccessException | ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断你一个类是否存在某个属性（字段）
     *
     * @param field 字段
     * @param obj   类对象
     * @return true:存在，false:不存在, null:参数不合法
     */
    public static Boolean isExistField(String field, Object obj) {
        if (obj == null || StringUtils.isEmpty(field)) {
            return false;
        }
        Object o = JSON.toJSON(obj);
        JSONObject jsonObj = new JSONObject();
        if (o instanceof JSONObject) {
            jsonObj = (JSONObject) o;
        }
        return jsonObj.containsKey(field);
    }
}
